package com.wl.controller;

import com.mysql.cj.util.StringUtils;
import com.wl.pojo.Users;
import com.wl.pojo.model.UserToken;
import com.wl.response.CommonReturnType;
import com.wl.service.UsersService;
import com.wl.service.impl.UsersServiceImpl;
import com.wl.util.FTPUtil;
import com.wl.util.MyUtil;
import com.wl.util.TokenUtils;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-08 19:01
 */
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private UsersService usersService = new UsersServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean b1 = checkToken(request, response);
        if (!b1) {
            MyUtil.responseData(response, CommonReturnType.fail("请登录后再执行此操作"));
            return;
        }
        checkToken(request, response);
        FTPUtil ftpUtil = new FTPUtil();
        String filePath = ftpUtil.uploadFolder(request, response);
        UserToken user = TokenUtils.getUser(request);
        Users users = new Users();
        users.setUserId(user.getUserId());
        users.setUserProfilePhoto(filePath);
        boolean b = usersService.update(users);
        if (b) {
            MyUtil.responseData(response, CommonReturnType.success(filePath));
        } else {
            MyUtil.responseData(response, CommonReturnType.fail(user.getUserProfilePhoto()));
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 检查用户是否登录
     *
     * @param request
     * @param response
     */
    @SneakyThrows
    protected boolean checkToken(HttpServletRequest request, HttpServletResponse response) {
        String token = TokenUtils.parseTokenToken(request);
        if (StringUtils.isNullOrEmpty(token)) {
            return false;
        }
        return true;
    }

}
